package top.lingkang.websocketlivechrome.ws;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

import java.io.FileReader;
import java.lang.reflect.Array;

/**
 * @author lingkang
 * Created by 2021/12/21
 */
@Component
public class VideoWebSocketHandler implements WebSocketHandler {

    public WebSocketSession session;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        this.session = session;
        if (session.getUri().toString().indexOf("zhubo") != -1) {
            if (WsHelper.zhuboSession != null && WsHelper.zhuboSession.isOpen()) { // 主播只能有一人
                session.close();
                return;
            }
            WsHelper.zhuboSession = session;
        } else {
            WsHelper.viewerSession.put(session.getId(), session);
        }

        WsHelper.sessionNumber++;
        System.out.println("有人加入：id=" + session.getId() + "。当前在线人数" + WsHelper.sessionNumber);
    }


    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        System.out.println(message.getClass());
        System.out.println(message);
        if (message.getPayload() instanceof String) {
            System.out.println(message.getPayload());
        }else if (message.getPayload() instanceof Array){
            System.out.println("Array");
        }else if (message.getPayload() instanceof BinaryMessage){
            BinaryMessage bm= (BinaryMessage) message.getPayload();
            System.out.println(bm.getPayload().toString());
        }
    }

    /**
     * 处理错误
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println("发生异常：" + exception.getMessage());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        WsHelper.sessionNumber--;
        System.out.println("有人关闭连接！当前在线人数" + WsHelper.sessionNumber);
        if (WsHelper.zhuboSession != null && session.getId().equals(WsHelper.zhuboSession.getId())) {
            WsHelper.zhuboSession.close();
        }
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
